package com.jiepos.mpos.biz.appInfM.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.AppInsAppHistoryDao;
import com.jiepos.mpos.common.dao.OrganizationDao;
import com.jiepos.mpos.common.entity.App_Ins_AppEntity;
import com.jiepos.mpos.common.entity.App_Ins_App_HistoryEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;


/**
 *
 *
 * <p>标题: —— 历史更新表类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos]
 * @Package com.jiepos.mpos.biz.appInfM.service
 * @author 余翼膑
 * @version 1.0
 * @since 2017年9月26号
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class HistoryService extends BaseService {

    @Autowired
    private AppInsAppHistoryDao historyDao;

    @Autowired
    private OrganizationDao organizationDao;

    /**
     * 查询APP更新历史信息信息列表json分页数据
     * @param pagination
     * @param appInsAppEntity
     * @return
     */
    public Map getHistoryAppList(HttpServletRequest request, Pagination pagination, App_Ins_AppEntity appInsAppEntity) {

        StringBuffer sb = getInitSql("t1").append(",");
        sb.append("t2.app_name_app,t1.ins_app_uuid,t1.ins_app_history_uuid as uuid,t1.app_version,t1.app_desc,t1.rec_id,t1.android_version_code,t1.android_update_md5,t1.android_apk_size， ");
        sb.append(" t3.ins_cd || '-' || t3.ins_cn_nm inst_name,t1.app_type||'-'||t4.code_desc as app_type ");
        sb.append(" FROM ");
        sb.append(DBConstant.Table.T_APP_INS_APP_HISTORY).append(" T1 LEFT JOIN  ");
        sb.append(DBConstant.Table.T_APP_INS_APP).append(" T2 ").append(" ON t1.ins_app_uuid = t2.ins_app_uuid ");
        sb.append(" LEFT JOIN  ");
        sb.append(DBConstant.Table.T_APP_INS_INF).append(" T3 ").append(" ON t2.ins_uuid = t3.ins_uuid  ");
        sb.append(" LEFT JOIN  ");
        sb.append(DBConstant.Table.T_APP_CODE_LIST).append(" t4 ON t1.app_type = t4.code_val and t4.code_tp='APP_TYPE' ");
        sb.append(" where 1 = 1 ");
        List list = new ArrayList();
        if (!StringUtils.isBlank(appInsAppEntity.getApp_name_app())) {
            sb.append( " and t2.app_name_app like ? " );
            list.add("%" + appInsAppEntity.getApp_name_app() + "%");
        }
        pagination.queryString = sb.toString();
      /*  pagination = getInsAuthSql(request, pagination, "t3", null);*/
        pagination = this.getOrderSql(pagination, "t1");
        return historyDao.getPaginationMap(pagination, "t1", list);
    }

    /**
     * 根据记录id查询实体对象
     * @param   ins_app_history_uuid
     * @return
     */
    public Map getHistoryAppById(String ins_app_history_uuid) {
        if(StringUtils.isBlank(ins_app_history_uuid) || ins_app_history_uuid.equals("undefined")){
            return new HashMap();
        }
        StringBuffer sb = getInitSql("t1").append(",");
        sb.append("t2.app_name_app,t1.ins_app_uuid,t1.ins_app_history_uuid,t1.app_type,t1.app_version,t1.app_desc,t1.rec_id,t1.android_version_code,t1.android_update_md5,t1.android_apk_size,  ");
        sb.append(" t3.ins_cd || '-' || t3.ins_cn_nm inst_name from ");
        sb.append(DBConstant.Table.T_APP_INS_APP_HISTORY);
        sb.append(" t1 LEFT JOIN ");
        sb.append(DBConstant.Table.T_APP_INS_APP).append(" t2 ON t1.ins_app_uuid = t2.ins_app_uuid");
        sb.append(" LEFT JOIN ");
        sb.append(DBConstant.Table.T_APP_INS_INF).append(" t3 on t3.ins_uuid = t2.ins_uuid ");
        sb.append(" WHERE T1.ins_app_history_uuid = ?");
        List<String> list = new ArrayList<>();
        list.add(ins_app_history_uuid);
        List<Map<String, Object>> results = historyDao.queryForList(getOrderSql(sb.toString(), "t1"), list);
        return results != null ? results.get(0) : new HashMap<String, Object>();

    }

    /**
     * 保存历史更新信息
     * @param   appHistoryEntity
     * @return
     */
    public String saveHistoryAppDetail(App_Ins_App_HistoryEntity appHistoryEntity, Map map) {
        //当前用户
        appHistoryEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
        /*if(org.apache.commons.lang.StringUtils.isBlank(appInsAppEntity.getIns_uuid())){
            appInsAppEntity.setIns_uuid(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_INS_UUID)));
        }*/
        if (!StringUtils.isBlank(appHistoryEntity.getIns_app_history_uuid())) {
            //修改
            appHistoryEntity = (App_Ins_App_HistoryEntity) this.saveCommonData(appHistoryEntity, map, "update");
            List noChangeList = new ArrayList();
            noChangeList.add("ins_app_history_uuid");
            noChangeList.add("rec_crt_ts");
            historyDao.update(appHistoryEntity, noChangeList);
        } else {
            //新增
            appHistoryEntity.setLast_oper_in(SystemConstant.OPER_ADD);
            appHistoryEntity.setIns_app_history_uuid(IDFactoryUtil.getUUID());
            App_Ins_App_HistoryEntity newHistoryAppEntity = (App_Ins_App_HistoryEntity) this.saveCommonData(appHistoryEntity, map, "null");
            historyDao.save(appHistoryEntity);
            //新增操作才需要更新机构app信息
            List paramList = new ArrayList();
            String updateInsSql = "update "+DBConstant.Table.T_APP_INS_APP+" set ";
            if (appHistoryEntity.getApp_type().equals(SystemConstant.APP_TYPE_ANDROID)) {
                //更新版本
                updateInsSql = updateInsSql + " android_version=? ";

            }else{
                updateInsSql = updateInsSql + " ios_version=? ";
            }
            updateInsSql = updateInsSql + " where ins_app_uuid=? and rec_st=?";
            paramList.add(appHistoryEntity.getApp_version());
            paramList.add(appHistoryEntity.getIns_app_uuid());
            paramList.add(SystemConstant.REC_ST_1);
            organizationDao.update(updateInsSql, paramList);
        }
        return appHistoryEntity.getIns_app_history_uuid();
    }
    /**
     * 所属机构树形
     * @param
     * @return
     */
    public List<Map<String, Object>> getInsAppInfTree(){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append("  SELECT T.INS_UUID ID, ")
                .append("  T.SUP_INS_UUID PID, ")
                .append("  T.INS_CD || '-' || T.INS_CN_NM NAME, ")
                .append("  t2.ins_app_uuid as INSUUID, ")
                .append("  T2.app_name_app AS APPNAME, ")
                .append("  (SELECT COUNT(1)  FROM T_APP_INS_INF  WHERE SUP_INS_UUID = T1.INS_UUID) CHILD_COUNT  ")
                .append("  FROM T_APP_INS_APP T1 ")
                .append("  inner JOIN T_APP_INS_INF T ")
                .append("  ON T.INS_UUID = T1.INS_UUID ")
                .append("  LEFT JOIN T_APP_INS_APP T2 ")
                .append("  ON T1.INS_UUID = T2.INS_UUID ")
                .append("  where 1=1 ");
        List<Map<String, Object>> ins = historyDao.queryForList(getOrderSql(sqlBuf.toString(), "T1"), null);
        return ins;
    }

    /**
     * 删除方法
     * @param ins_app_history_uuids 主键唯一标识
     */
    public void deleteHistoryAppByIds(String ins_app_history_uuids) {
        historyDao.deleteByStatus("ins_app_history_uuid",ins_app_history_uuids);
    }

    /**
     * 获取更新历史最新uuid
     * @param ins_app_uuid
     * @return
     */
    public String getHistoryAppUuuid(String ins_app_uuid) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT T.Ins_App_History_Uuid ")
                .append("  FROM ").append(DBConstant.Table.T_APP_INS_APP_HISTORY)
                .append(" T  where t.ins_app_uuid = ? and  t.rec_st = "+SystemConstant.REC_ST_1+ " order by rec_upd_ts desc");
        List list = new ArrayList();
        list.add(ins_app_uuid);
        List<Map> resultList = historyDao.queryForList(sql.toString(), list);
        if(CollectionUtil.isEmpty(resultList)){
            return null;
        }
        return String.valueOf(resultList.get(0).get("Ins_App_History_Uuid"));
    }
}
